<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use think\Db;

class CaipiaoController extends AdminBaseController {

	public function _initialize() {
		$adminSettings = cmf_get_option('admin_settings');
		if (empty($adminSettings['admin_password']) || $this->request->path() == $adminSettings['admin_password']) {
			$adminId = cmf_get_current_admin_id();
			if (empty($adminId)) {
				session("__LOGIN_BY_CMF_ADMIN_PW__", 1); //设置后台登录加密码
			}
		}

		parent::_initialize();
	}

	/**
	 * 后台首页
	 */
	public function index() {
		$kefu = Db::table("kefu")->find();
		$this->assign("kefu", $kefu);
		return $this->fetch();
	}

	public function post() {
		$post = $_POST;
		foreach ($_FILES as $key => $value) {
			# code...
			if ($value['name']) {
				$res = $this->uploads($value);
				$res = json_decode($res);
				if ($res->status) {
					$post[$key] = $res->path;
				} else {
					echo $res->msg;
				}

			}
		}
		$kefu = Db::table("kefu")->find();
		$rt = 0;
		if ($kefu) {
			$rt = Db::table("kefu")->where(['id' => $kefu['id']])->update($post);
		} else {
			$rt = Db::table("kefu")->insert($post);
		}
		$this->success(lang("EDIT_SUCCESS"), url("admin/caipiao/index"));
	}

	public function uploads($file) {

		if ((($file["type"] == "image/gif")
			|| ($file["type"] == "image/jpeg")
			|| ($file["type"] == "image/pjpeg"))
			&& ($file["size"] < 20000000)) {
			if ($file["error"] > 0) {
				echo "Return Code: " . $file["error"] . "<br />";
				return json_encode(array("status" => 0, "msg" => "Return Code: " . $file["error"]));
			} else {
				// echo "Upload: " . $file["name"] . "<br />";
				// echo "Type: " . $file["type"] . "<br />";
				// echo "Size: " . ($file["size"] / 1024) . " Kb<br />";
				// echo "Temp file: " . $file["tmp_name"] . "<br />";
				// if (file_exists("upload/" . $file["name"])) {
				// 	echo $file["name"] . " already exists. ";
				// } else {
				move_uploaded_file($file["tmp_name"],
					"upload/" . $file["name"]);
				return json_encode(array("status" => 1, "msg" => "success", "path" => "/" . $file["name"]));
				// echo "Stored in: " . "upload/" . $file["name"];
				// }
			}
		} else {
			return json_encode(array("status" => 0, "msg" => "Invalid file"));
		}
	}
}
